// 每一个 relation 结构:
// [
//   "R2", // 唯一标识
//   "债务人公司-债权人公司", // 关系类型
//   [
//     ["Arg1", "T2"], // 关系对象1（from）
//     ["Arg2", "T1"] // 关系对象2（to）
//   ]
// ],

export function formatRelations (relations, relationTypesMap, entities) {
  return relations.map(i => {
    const type1 = i[2][0][1]
    const type2 = i[2][1][1]
    const fromEntity = getEntity(type1, entities)
    const toEntity = getEntity(type2, entities)
    const range1 = fromEntity[2][0]
    const range2 = toEntity[2][0]

    const start = range1[0] <= range2[0] ? range1[0] : range2[0]
    const end = range1[1] >= range2[1] ? range1[1] : range2[1]

    let left, right
    if (range1[0] <= range2[0]) {
      left = type1
      right = type2
    } else {
      left = type2
      right = type1
    }

    return {
      start,
      end,
      left,
      right,
      from: type1,
      to: type2,
      fromEntity,
      toEntity,
      id: i[0],
      type: i[1],
      text: relationTypesMap[i[1]].name
    }
  })
}

function getEntity (type, entities) {
  return entities.find(i => {
    return i[0] === type
  })
}

export function getRelations (tspan, relations) {
  // 空行不显示信息
  if (tspan.type === 'empty') {
    return undefined
  }

  const { start, end } = tspan
  const arr = []
  relations.forEach(i => {
    if (i.start > end || i.end < start) return
    // 需要拷贝，不能影响计算属性
    const relation = Object.assign({
      level: 1
    }, i)
    arr.push(relation)
  })
  return arr.length > 0 ? arr : undefined
}
